﻿using System;
using System.Configuration;

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

using BlueSky;

namespace BlueSky.IoC.Unity
{
    /// <summary>
    /// IoCUnityContainer class.
    /// </summary>
    public class IoCUnityContainer : IIoCContainer
    {
        protected IUnityContainer _container = new UnityContainer();
        /// <summary>
        /// Constructor.
        /// </summary>
        public IoCUnityContainer()
        {            
        }        
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="sectionName">The configuration section path and name.</param>
        public IoCUnityContainer(string sectionName)
        {
            UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection(sectionName);
            section.Containers.Default.Configure(_container);
        }


        #region IIoCContainer Members

        public object Resolve(Type type)
        {
            return _container.Resolve(type);
        }

        public object Resolve(Type type, string name)
        {
            return _container.Resolve(type, name);
        }

        public T Resolve<T>()
        {
            return _container.Resolve<T>();
        }

        public T Resolve<T>(string name)
        {
            return _container.Resolve<T>(name);
        }

        public void Register<TFrom, TTo>() where TTo : TFrom
        {
            _container.RegisterType<TFrom, TTo>();
        }

        public void Register<TFrom, TTo>(string name) where TTo : TFrom
        {
            _container.RegisterType<TFrom, TTo>(name);
        }

        public void Register(Type typeForm, Type typeTo)
        {
            _container.RegisterType(typeForm, typeTo);
        }

        public void Register(Type typeForm, Type typeTo, string name)
        {
            _container.RegisterType(typeForm, typeTo, name);
        }

        public void Register<T>(T instance)
        {
            _container.RegisterInstance<T>(instance);
        }

        public void Register<T>(T instance, string name)
        {
            _container.RegisterInstance<T>(name, instance);
        }

        public void Register(Type type, object instance)
        {
            _container.RegisterInstance(type, instance);
        }

        public void Register(Type type, object instance, string name)
        {
            _container.RegisterInstance(type, name, instance);
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            if (_container != null)
                _container.Dispose();
            _container = null;
        }

        #endregion        
    }
}
